package com.itboye.sunsun.person.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.sunsun.HomeFragment;
import com.itboye.sunsun.MainActivity;
import com.itboye.sunsun.R;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.ConfigBean;
import com.itboye.sunsun.clipimage.ClipActivity;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.controller.UnLoginState;
import com.itboye.sunsun.custome.RoundImage;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.personsetting.ui.SetEmailActivity;
import com.itboye.sunsun.personsetting.ui.SetNickNameActivity;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.CameraPopupWindow;
import com.itboye.sunsun.utils.ImageCompress;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.utils.XImageLoader;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.UploadImage;
import com.itboye.sunsun.volley.UploadImage.OnUploadlistener;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsun.wxapi.WXEntryActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.message.PushAgent;

public class PersonSettingActivity extends BaseActivity implements
		OnClickListener, OnUploadlistener {

	public static String AVARTACTION = "com.itboye.avart";

	public static String EMAILACTION = "com.itboye.email";
	private RelativeLayout nicknamerela;
	private RelativeLayout phonerela;
	private RelativeLayout emailrela;
	private RelativeLayout wechatrela;
	private RelativeLayout aboutrela;
	private RelativeLayout protocalrela;
	private RelativeLayout backrela;
	private RelativeLayout uploadrela;
	private RelativeLayout exitrela;
	private DisplayImageOptions options;
	private RoundImage avatarview;
	private RoundImage wechatview;
	private TextView phone;
	private TextView versionname;
	private TextView nicktext;
	private IWXAPI api;
	private static final String APP_ID = "wxa30658c4f4f6bbf4";
	private TextView emailtext;
	private String phonenumber;

	public static String EXITCHANGE = "com.itboye.sunsun.person.exit";
	// 点击数字拨打电话
	private TextView textPhone, textNumPhone;

	private String localSelectPath;

	private CameraPopupWindow mCameraPopupWindow;
	TextView hasNew;

	RelativeLayout addSunSun;
	protected ArrayList<ConfigBean> arConfig;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);

		api = WXAPIFactory.createWXAPI(App.ctx, APP_ID);
		setContentView(R.layout.activity_personsetting);
		// 例如直接这样使用不会报空指针异常
		// nicknamerela.setBackgroundColor(R.color.background_gray);

		getVersionAvaliable();
		// 微信按钮
		String openid = (String) SPUtils.get(App.ctx, null,
				SPContants.WX_Openid, "");
		// Toast.makeText(App.ctx, openid, 0).show();
		if (openid.equals("")) {
			wechatview.setVisibility(View.GONE);
		} else {
			wechatview.setVisibility(View.VISIBLE);
		}
		emailtext.setClickable(false);
		nicktext.setClickable(false);
		setStatusBarColor(R.color.top_blue);
		phonenumber = (String) SPUtils
				.get(App.ctx, null, SPContants.MOBILE, "");
		// Log.v("mobilephone", phonenumber+".... ");
		if (!phonenumber.equals(""))

		{
			try {
				String hintphone = phonenumber.substring(0, 3) + "****"
						+ phonenumber.substring(7, 11);
				phone.setText(hintphone);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		nicktext.setText((String) SPUtils.get(App.ctx, null, SPContants.NICK,
				""));
		emailtext.setText((String) SPUtils.get(App.ctx, null, SPContants.EMAIL,
				""));
		initavatar();

		IntentFilter intentFilterEmail = new IntentFilter(
				SetEmailActivity.EMAILACTION);
		this.registerReceiver(emailBroadcastReceiver, intentFilterEmail);

		IntentFilter wechatFilterEmail = new IntentFilter(
				WXEntryActivity.NotifyPerson);
		this.registerReceiver(wechatBroadcastReceiver, wechatFilterEmail);

		// 显示版本号
		try {
			PackageManager pm = App.ctx.getPackageManager();
			PackageInfo info = pm.getPackageInfo(App.ctx.getPackageName(), 0);
			String appVersion = info.versionName;
			versionname.setText(appVersion);
		} catch (Exception e) {

		}

		// findViewById(R.id.addSunSun).setOnClickListener(new OnClickListener()
		// {
		// int count = 0;
		// long time;
		//
		// @Override
		// public void onClick(View v) {
		//
		// if (System.currentTimeMillis() - time > 500) {
		// count = 0;
		//
		// } else {
		// count++;
		// }
		//
		// time = System.currentTimeMillis();
		// if (count == 10) {
		// throw new RuntimeException("test exception....");
		// }
		// }
		// });
	}

	ConfigBean newConfigBean = null;
	int newVersion = 0;
	int oldVersion = 0;

	public void getVersionAvaliable() {
		MyJsonRequest.Builder<ArrayList<ConfigBean>> builder = new MyJsonRequest.Builder<ArrayList<ConfigBean>>()
				.apiVer("100").typeKey("BY_Config_app")
				.requestListener(new XRequestListener<ArrayList<ConfigBean>>() {

					@Override
					public void onResponse(ArrayList<ConfigBean> bean) {
						arConfig = bean;
						for (ConfigBean configBean : bean) {
							if (configBean.getName().equals(
									"android_xiuxian_version")) {
								newConfigBean = configBean;
								newVersion = Integer.parseInt(configBean
										.getValue().replace(".", ""));
								break;
							}
						}
						oldVersion = HomeFragment.getVersionCode();
						if (newVersion > oldVersion) {
							hasNew.setVisibility(View.VISIBLE);
						} else {
							hasNew.setVisibility(View.GONE);
						}
					}

				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						System.out.println(msg + "----" + code);
						// onPullDownError(adapter, xlistview, exception, code,
						// msg);
					}
				});

		MyJsonRequest<ArrayList<ConfigBean>> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	UIAlertView02 delDialog = null;

	public void onManager(ConfigBean appUpdateBean) {
		delDialog = new UIAlertView02(this, appUpdateBean.getValue(), "有更新啦!",
				"以后再说", "立即更新");
		delDialog.show();

		delDialog.setClicklistener(new UIAlertView02.ClickListenerInterface() {

			public void doLeft() {
				delDialog.dismiss();
			}

			public void doRight() {
				String url = "";
				delDialog.dismiss();
				for (ConfigBean configBean : arConfig) {
					if ("android_xiuxian_url".equals(configBean.getName())) {
						url = configBean.getValue();
						break;
					}
				}
				if (!url.equals("")) {
					Uri uri = Uri.parse(url);
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setData(uri);
					startActivity(intent);
					// Intent intent = new Intent(getActivity(),
					// WebActivity.class);
					// intent.putExtra("url", url);
					// startActivity(intent);
				} else {
					Toast.makeText(PersonSettingActivity.this, "下载地址有误", 0)
							.show();
					// Byalert.alert("下载地址有误");
				}
			}
		});
		// UpdateManager manager = new UpdateManager(this,
		// "ceshi ",
		// "http://a.app.qq.com/o/simple.jsp?pkgname=com.itboye.sunsunhome","1.1.3");
		// manager.checkUpdateInfo();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.nicknamerela:
			Intent intent = new Intent(PersonSettingActivity.this,
					SetNickNameActivity.class);
			startActivityForResult(intent, 1);
			break;
		case R.id.emailrela:
			Intent intent1 = new Intent(PersonSettingActivity.this,
					SetEmailActivity.class);
			startActivityForResult(intent1, 3);
			break;
		case R.id.backrela:
			this.finish();
			break;
		case R.id.uploadrela:
			// TODO Auto-generated method stub
			mCameraPopupWindow = new CameraPopupWindow(
					PersonSettingActivity.this, onclicklister);
			mCameraPopupWindow.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);

			break;
		case R.id.addSunSun:
			if (newVersion > oldVersion) {
				onManager(newConfigBean);
			} else {
				Toast.makeText(this, "当前已经是最新版本", 0).show();
			}
			break;
		case R.id.exitrela:
			exit();
			break;
		case R.id.wechatrela:
			welongin();
			break;
		case R.id.aboutrela:

			Intent intent3 = new Intent(PersonSettingActivity.this,
					AboutActivity.class);
			startActivity(intent3);
			break;
		case R.id.protocalrela:
			Intent intent4 = new Intent(PersonSettingActivity.this,
					ProtocalActivity.class);
			startActivity(intent4);
			break;
		case R.id.phonerela:
			Intent intent5 = new Intent(PersonSettingActivity.this,
					ChangeBindActivity.class);
			intent5.putExtra("phonenumber", phonenumber);
			startActivity(intent5);
			break;
		case R.id.textPhone:

			break;
		default:
			break;

		}

	}

	private OnClickListener onclicklister = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.open_camera:
				/**
				 * 打开照相机
				 */
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent,
							CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
				} else {
					Toast.makeText(PersonSettingActivity.this, "请确认已经插入SD卡", 0)
							.show();
				}
				break;
			case R.id.pick_image:
				Intent intent2 = new Intent();
				intent2.setType("image/*");// 可选择图片视频
				// 修改为以下两句代码

				intent2.setAction(Intent.ACTION_PICK);
				intent2.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 使用以上这种模式，并添加以上两
				// intent.setDataAndType(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				// "image/*");
				startActivityForResult(intent2, 0);
				break;
			case R.id.img:
				break;
			default:
				break;
			}
		}
	};

	private String picture_name;

	private String fileName;
	// 使用相机拍照
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;
	public static final int IMAGE_COMPLETE = 6; // 结果

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == 0) {
				/**
				 * 当选择的图片不为空的话，在获取到图片的途径
				 */
				Uri selectedImage = data.getData();
				localSelectPath = null;
				// Cursor cursor = this.getContentResolver().query(
				// data.getData(), null, null, null, null);
				// cursor.moveToFirst();
				// int columnIndex = cursor.getColumnIndex("_data");
				// localSelectPath = cursor.getString(columnIndex);
				localSelectPath = getRealPathFromURI(selectedImage);
				localSelectPath = ImageCompress.compress(localSelectPath);
				Intent intent2 = new Intent(PersonSettingActivity.this,
						ClipActivity.class);
				intent2.putExtra("path", localSelectPath);
				startActivityForResult(intent2, IMAGE_COMPLETE);
			} else if (requestCode == 3) {
				// Toast.makeText(App.ctx, "haha", 0).show();
				emailtext.setText("" + data.getStringExtra("email"));
			} else if (requestCode == 1) {
				nicktext.setText("" + data.getStringExtra("nickname"));
			} else if (requestCode == 6) {
				UploadImage.getInstance().execute(localSelectPath, this);
				mCameraPopupWindow.dismiss();
			} else if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
					&& resultCode == RESULT_OK) {
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					return;
				}
				picture_name = android.text.format.DateFormat.format(
						"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
						+ ".jpg";
				Bundle bundle = data.getExtras();
				Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
				// SavePicInLocal(bitmap);
				FileOutputStream b = null;
				File file = new File("/sdcard/Image/");
				file.mkdirs();// 创建文件夹
				fileName = "/sdcard/Image/" + picture_name;

				try {
					b = new FileOutputStream(fileName);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				// fileName=ImageCompress.compress(fileName);
				UploadImage.getInstance().execute(fileName, this);
				mCameraPopupWindow.dismiss();

			}
		}
	}

	/**
	 * This method is used to get real path of file from from uri<br/>
	 * http://stackoverflow.com/questions/11591825/how-to-get-image-path-just-
	 * captured-from-camera
	 * 
	 * @param contentUri
	 * @return String
	 */
	public String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = this.managedQuery(contentUri, proj, null, null,
					null);
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	/**
	 * 该调用系统的图片截取方法已被遗弃，华为手机报错
	 * 
	 * @param url
	 */
	public void startCrop(Uri url) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(url, "image/*");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		// intent.putExtra("return-data", true);
		startActivityForResult(intent, 2);

	}

	// 显示头像
	public void initavatar() {

		String uri = (String) SPUtils.get(App.ctx, null, SPContants.AVATAR_URL,
				"");
		XImageLoader.load(uri, avatarview);

	}

	@Override
	public void OnSuccess(String resultData) {
		Toast.makeText(App.ctx, "上传成功", 0).show();
		initavatar();
		Intent intent = new Intent(AVARTACTION);
		sendBroadcast(intent);
	}

	@Override
	public void OnError(String resultData) {
		Toast.makeText(App.ctx, resultData, 0).show();

	}

	BroadcastReceiver emailBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			nicktext.setText(intent.getStringExtra("email"));
			Toast.makeText(App.ctx, "haha", 0).show();
		};
	};
	BroadcastReceiver wechatBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			wechatview.setVisibility(View.VISIBLE);
		};
	};

	public void deleteInfo() {

		SharedPreferences sp = getSharedPreferences("share_by_data",
				MODE_PRIVATE);
		sp.edit().putString(SPContants.USER_ID, "")
				.putString(SPContants.MOBILE, "")
				.putString(SPContants.EMAIL, "").putString(SPContants.NICK, "")
				.putString(SPContants.PASSWORD, "")
				.putString(SPContants.AVATAR_URL, "")
				.putString(SPContants.USERNAME, "")
				.putString(SPContants.WX_Openid, "")
				.putBoolean(SPContants.IS_LOGINED, false).commit();
	}

	public void exit() {

		try {
			PushAgent.getInstance(App.ctx)
					.deleteAlias(
							(String) SPUtils.get(App.ctx, null,
									SPContants.USER_ID, ""), "sunsun");
		} catch (Throwable e) {
			e.printStackTrace();
		}
		deleteInfo();
		LoginController.setLoginState(new UnLoginState());

		Intent intent = new Intent(PersonSettingActivity.this,
				MainActivity.class);
		startActivity(intent);
		Intent intent1 = new Intent(EXITCHANGE);
		sendBroadcast(intent1);
		this.finish();

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(emailBroadcastReceiver);
		unregisterReceiver(wechatBroadcastReceiver);
	}

	// 微信绑定
	private void welongin() {
		final SendAuth.Req req = new SendAuth.Req();
		req.scope = "snsapi_userinfo";
		req.state = "none";

		req.transaction = "bind";
		api.sendReq(req);
		// finish();

	}

}
